package com.oneday.ashop.webgate.user;

import com.oneday.ashop.core.base.util.StringUtil;
import com.oneday.ashop.core.entity.CommonConstant;
import com.oneday.ashop.core.entity.Suggestion;
import com.oneday.ashop.core.entity.User;
import com.oneday.ashop.core.entity.book.Blog;
import com.oneday.ashop.webgate.base.file.BaseFileOperate;
import com.oneday.ashop.webgate.base.ftp.SFtpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.CropImageFilter;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User:bob.yang
 * Date 2015/7/15 0015
 */
@Service
public class UserService {

    /**
     * 默认头像
     */
    public static final String USER_IMG_URL_DEFAULT = "http://139.129.12.155:8089/tongyong.jpg";

    @Autowired
    UserDao userDao;

    public void addUser(String name, String password, String address) {
       userDao.addUser(name, password, address);
    }

    public void addUser(String name, String password) {
        userDao.addUser(name, password, null);
    }

    /**
     * 验证注册信息是否正确
     * @param name
     * @param password
     * @param password2
     * @return
     */
    public int checkRegInfo(String name, String password, String password2) {
        if (name.isEmpty() || password.isEmpty() || password2.isEmpty()) {
            return 1;
        } else if(!password.equals(password2)){
            return 2;
        } else if(checkUserExists(name)) {
            return 3;
        }

        return 0;
    }

    /**
     * 验证用户是否已存在
     * @param name
     * @return
     */
    private boolean checkUserExists(String name) {
        if (userDao.queryUserByName(name)) {
            return true;
        }

        return false;
    }

    public void deleteUser(String name) {
        userDao.deleteUser(name);
    }

    public void updateUser(String name, String password, String address) {
        userDao.updateUser(name, password, address);
    }

    public List<User> queryUser(String password) {
        List<User> userList = userDao.queryUser(password);
        return userList;
    }

    public boolean queryUserByName(String name) {
        return userDao.queryUserByName(name);
    }

    /**
     * 登陆
     * @param account
     * @param password
     * @return
     */
    public User login(String account, String password) {
        User user = userDao.findUser(account);
        if(user == null) {
            return null;
        }
        if(!user.getPassword().equals(password)) {
            return null;
        }
        return user;
    }

    /**
     * 注册
     * @param name
     * @param email
     * @param password
     * @param city
     * @param telephone
     * @param validateCode
     * @param isPermit
     * @return
     */
    public int[] register(String name, String email, String password, String city, String telephone, String validateCode, String isPermit) {
        //校验手机号码
       if(!("".equals(telephone) || !StringUtil.checkTelephone(telephone))) {
           return new int[]{1};
       }
        //校验邮箱
        if(!("".equals(email) || !StringUtil.checkEmail(email))) {
            return new int[]{2};
        }
        //昵称过长
        if("".equals(name) || name.length() > 7) {
            return new int[]{3};
        }
        //密码校验
        Pattern pattern = Pattern.compile("^[0-9a-zA-Z_]{5,20}$");
        Matcher matcher = pattern.matcher(password);
        if(!matcher.matches()) {
            return new int[]{4};
        }
        //用户未同意协议不能注册
        if(!isPermit.equals("1")) {
            return new int[]{5};
        }
        //验证码不正确
        if(!"12345".equals(validateCode)) {
            return new int[]{6};
        }
        //用户已经存在
        User user = userDao.findUser(telephone);
        if(user == null) {
            user = userDao.findUser(email);
            if(user != null) {
                return new int[]{7};
            }
        }else {
            return new int[]{7};
        }
        user = new User();
        user.setPassword(password);
        user.setName(name);
        user.setAddress(city);
        user.setEmail(email);
        user.setTelephone(telephone);
        user.setAddTime(new Date());
        user.setImgUrl(USER_IMG_URL_DEFAULT);
        userDao.addUser(user);
        return new int[]{0};
    }

    /**
     * 网站评价
     * @param evaluation
     * @param advice
     * @param reason
     */
    public void suggest(Integer evaluation, String advice, String reason) {
        Suggestion suggestion = new Suggestion();
        suggestion.setAddTime(new Date());
        suggestion.setEvaluation(evaluation);
        suggestion.setReason(reason);
        suggestion.setAdvice(advice);
        userDao.addSuggestion(suggestion);
    }

    /**
     * 根据用户号查找用户
     * @param userId
     * @return
     */
    public User findUser(Integer userId) {
        return userDao.findUser(userId);
    }

    /**
     * 上传头像
     * @param icon
     * @return
     */
    public String uploadImg(MultipartFile icon) {
        SFtpUtil.upload(icon, icon.getOriginalFilename(),  CommonConstant.IMAGE_PATH);
        return "http://139.129.12.155:8089/" + icon.getOriginalFilename();
    }

    /**
     * 截取图片
     * @param uid 用户号
     * @param imgUrl 图片路径
     * @param x 横坐标
     * @param y 纵坐标
     * @param width 宽
     * @param height 高
     */
    public String cropImg(Integer uid ,String imgUrl, int x, int y, int width, int height) {
        int index = imgUrl.lastIndexOf('.');
        String imgType = imgUrl.substring(index + 1);
        String newImgUrl ;
        try {
            newImgUrl = BaseFileOperate.cropImg(imgUrl, x, y, width, height, imgType);
        } catch (MalformedURLException e) {
           throw new RuntimeException();
        }
        userDao.updateImgUrl(uid, newImgUrl);
        return newImgUrl;
    }

}
